package com.hejia.bulbul.controller;

import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.hejia.alauda.entity.Honor;
import com.hejia.alauda.service.HonorService;
import com.hejia.alauda.utils.HttpResponse;
import com.hejia.alauda.utils.Pager;
import com.hejia.alauda.utils.PagerHelper;

@Controller
@RequestMapping("honor")
public class HonorController extends BaseController {

	private static final Log logger = LogFactory
			.getLog(QuestionController.class);

	@Resource
	private HonorService honorService;

	@RequestMapping
	public String list(Model model, Pager<Honor> pager, String title) {

		pager = this.honorService.findHonors(pager, title);
		model.addAttribute("title", title);
		model.addAttribute("honors", pager);

		// 分页
		PagerHelper<Honor> helper = new PagerHelper<>();
		helper.setPager(pager);
		Map<String, String> map = new HashMap<>();
		if (title != null) {
			map.put("title", title);
		}
		helper.setParams(map);
		helper.setBaseUrl("/honor");
		model.addAttribute("pagerHelper", helper);

		return "honor/list";
	}

	@RequestMapping(method = RequestMethod.POST)
	@ResponseBody
	public HttpResponse add(Honor honor) {

		HttpResponse response = new HttpResponse();

		try {
			honor = honorService.addHonor(honor);
			response.setCode(HttpResponse.CODE_OK);
			response.setStatus(HttpResponse.STATUS_SUCCESS);
			response.setMessage("添加资质荣誉成功");
			response.setData(honor);

		} catch (Exception e) {
			logger.error("添加资质荣誉失败", e);
			response.setCode(HttpResponse.CODE_INTERNAL_SERVER_ERROR);
			response.setStatus(HttpResponse.STATUS_FAIL);
			response.setMessage("添加资质荣誉失败 " + e.getMessage());
			response.setData(honor);
		}

		return response;
	}

	@RequestMapping(value = "{id}", method = RequestMethod.DELETE)
	@ResponseBody
	public HttpResponse delete(@PathVariable Long id) {

		HttpResponse response = new HttpResponse();

		try {
			honorService.deleteHonor(id);
			response.setCode(HttpResponse.CODE_OK);
			response.setStatus(HttpResponse.STATUS_SUCCESS);
			response.setMessage("删除资质荣誉成功");

		} catch (Exception e) {
			logger.error("删除资质荣誉失败", e);
			response.setCode(HttpResponse.CODE_INTERNAL_SERVER_ERROR);
			response.setStatus(HttpResponse.STATUS_FAIL);
			response.setMessage("删除资质荣誉失败 " + e.getMessage());
		}

		return response;
	}

}
